package ar.com.ford.it.fullEconomics.view.action;

import java.util.Collection;
import java.util.LinkedList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;
import ar.com.ford.it.fullEconomics.exception.FullEconomicsException;
import ar.com.ford.it.fullEconomics.facade.CommodityFacade;
import ar.com.ford.it.fullEconomics.facade.CostStructureFacade;
import ar.com.ford.it.fullEconomics.facade.SupplierFacade;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesc03Subcoststr;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesg01Plant;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp01Part;
import ar.com.ford.it.fullEconomics.persistence.dto.Teess01Supplier;
import ar.com.ford.it.fullEconomics.struct.OptionCombo;
import ar.com.ford.it.fullEconomics.view.form.SubCostStructureDetailForm;
import ar.com.ford.it.fullEconomics.wslx.FullEconomicsWslxUser;
import ar.com.ford.it.webengine.facade.FacadeProvider;
import ar.com.ford.it.webengine.struts.AbstractBaseAction;
import ar.com.ford.it.webengine.struts.FordActionMapping;
import ar.com.ford.it.webengine.websession.WebSession;
import com.ford.it.persistence.PersistenceException;

public class SubCostStructureDetailAction extends AbstractBaseAction {

    private Collection getComboSupplierTypes(HttpServletRequest request) {
        LinkedList<OptionCombo> list = new LinkedList<OptionCombo>();
        MessageResources resources = (MessageResources) request
                .getAttribute(org.apache.struts.Globals.MESSAGES_KEY);

        list.add(new OptionCombo("-1", resources
                .getMessage("label.selectOption")));
        list.add(new OptionCombo("F", resources.getMessage("label.ford")));
        list.add(new OptionCombo("C", resources.getMessage("label.custom")));

        return list;
    }

    private Collection getComboPartClasses(HttpServletRequest request) {
        LinkedList<OptionCombo> list = new LinkedList<OptionCombo>();
        MessageResources resources = (MessageResources) request
                .getAttribute(org.apache.struts.Globals.MESSAGES_KEY);

        list.add(new OptionCombo("-1", resources
                .getMessage("label.selectOption")));
        list.add(new OptionCombo("F", resources.getMessage("label.ford")));
        list.add(new OptionCombo("C", resources.getMessage("label.custom")));

        return list;
    }

    /**
     * Chequea si existe el supplier y en caso de que no exista setea el mensaje
     * de error
     * 
     * @param facade
     * @param plant
     * @param supplier
     * @return
     * @throws FullEconomicsException
     * @throws PersistenceException
     */
    private boolean supplierExists(SupplierFacade facade, Teesg01Plant plant,
                                   Teess01Supplier supplier,
                                   HttpServletRequest request)
            throws FullEconomicsException {
        boolean ret = true;
        ActionMessages am = null;
        MessageResources messageResources = null;

        supplier.setEess01PlantCodeC(plant);
        supplier = facade.getSupplierByPk(supplier);

        if (supplier == null) {
            am = new ActionMessages();
            messageResources = (MessageResources) getResources(request);
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                    "error.notExists.m", messageResources
                            .getMessage("supplier.label.supplier")));
            saveErrors(request, am);
            ret = false;
        }

        return ret;
    }

    /**
     * Chequea si la parte existe
     * 
     * @param facade
     * @param plant
     * @param partClass
     * @param partPrefix
     * @param partBase
     * @param partSuffix
     * @param request
     * @return
     * @throws FullEconomicsException
     */
    private boolean partExists(CommodityFacade facade, Teesg01Plant plant,
                               Teesp01Part part, HttpServletRequest request)
            throws FullEconomicsException {
        boolean ret = true;
        ActionMessages am = null;
        MessageResources messageResources = null;

        part.setEesp01PlantCodeC(plant);
        part = facade.findPartByPk(part);

        if (part == null) {
            am = new ActionMessages();
            messageResources = (MessageResources) getResources(request);
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                    "error.notExists.f", messageResources
                            .getMessage("part.label")));
            saveErrors(request, am);
            ret = false;
        }

        return ret;
    }

    /**
     * Chequea si existe la pieza. Si no existe devuelve false y ademas setea el
     * mensaje de error.
     * 
     * @param facade
     * @param plant
     * @param partClass
     * @param partPrefix
     * @param partBase
     * @param partSuffix
     * @param request
     * @return
     * @throws FullEconomicsException
     */
    private boolean supplyExists(CommodityFacade facade, Teesg01Plant plant,
                                 Teesp01Part part, Teess01Supplier supplier,
                                 HttpServletRequest request)
            throws FullEconomicsException {
        boolean ret = true;
        Collection<Teesp01Part> parts = null;
        ActionMessages am = null;

        part.setEesp01PlantCodeC(plant);
        parts = facade.findParts(part, null, null, supplier
                .getEess01SupplierClassCodeC(), supplier
                .getEess01SupplierCodeC());

        if (parts == null || parts.isEmpty()) {
            am = new ActionMessages();
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                    "subCostStructure.detail.error.supply"));
            saveErrors(request, am);
            ret = false;
        }

        return ret;
    }

    /**
     * 
     */
    public ActionForward initPage(FordActionMapping mapping,
                                  ActionForm actionForm,
                                  HttpServletRequest request,
                                  HttpServletResponse response,
                                  WebSession webSession, ActionMessages msgs,
                                  ActionMessages warns, ActionMessages errorMsgs) {
        SubCostStructureDetailForm form = (SubCostStructureDetailForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        Teesc03Subcoststr subCostStr = (Teesc03Subcoststr) request
                .getAttribute("subCostStrSelected");
        String dependencyPath = null;
        Integer tier = null;

        dependencyPath = (String) request.getAttribute("dependencyPath");
        tier = (Integer) request.getAttribute("tier");
        form.setSubCostStr(subCostStr);
        form.setDetails(tier.toString(), dependencyPath);
        form.setPartClassesCol(this.getComboPartClasses(request));
        request.getSession().setAttribute("partClassesCol",
                form.getPartClassesCol());
        form.setSupplierTypesCol(this.getComboSupplierTypes(request));
        request.getSession().setAttribute("supplierTypesCol",
                form.getSupplierTypesCol());
        return mapping.findForward("success");
    }

    /**
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward saveSubCostStructure(FordActionMapping mapping,
                                              ActionForm actionForm,
                                              HttpServletRequest request,
                                              HttpServletResponse response,
                                              WebSession webSession,
                                              ActionMessages msgs,
                                              ActionMessages warns,
                                              ActionMessages errorMsgs) {
        SubCostStructureDetailForm form = (SubCostStructureDetailForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        CostStructureFacade costStructurefacade = (CostStructureFacade) FacadeProvider
                .getFacade(request, CostStructureFacade.class);
        SupplierFacade supplierFacade = (SupplierFacade) FacadeProvider
                .getFacade(request, SupplierFacade.class);
        CommodityFacade commodityFacade = (CommodityFacade) FacadeProvider
                .getFacade(request, CommodityFacade.class);
        String forward = "success";

        try {
            if (!form.getSupplier().getEess01SupplierClassCodeC().equals("-1")) {
                // Si selecciono algun Supplier

                if (this.supplierExists(supplierFacade, user.getTeesg01Plant(),
                        form.getSupplier(), request)) {
                    if (!form.getPart().getEesp01PartClassCodeC().equals("-1")) {
                        // Si selecciono algun Part debe existir el Supply
                        
                        if (this.partExists(commodityFacade, user
                                .getTeesg01Plant(), form.getPart(), request)) {
                            if (this.supplyExists(commodityFacade, user
                                    .getTeesg01Plant(), form.getPart(), form
                                    .getSupplier(), request)) {
                                costStructurefacade.updateSubCostStructure(
                                        user, form.getSubCostStrForUpdate());
                            } else {
                                forward = "noSuccess";
                            }
                        } else {
                            forward = "noSuccess";
                        }
                    } else {
                        // Si selecciono Supplier y no Part hago update porque Part no es requerido

                        costStructurefacade.updateSubCostStructure(user, form
                                .getSubCostStrForUpdate());
                    }
                } else {
                    forward = "noSuccess";
                }
            } else {
                // Si no selecciono ningun Supplier hago update porque no es requerido

                costStructurefacade.updateSubCostStructure(user, form
                        .getSubCostStrForUpdate());
            }
        } catch (FullEconomicsException e) {
            ActionMessages am = new ActionMessages();
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward(forward);
    }

    /**
     * Vuelve a la pantalla de Cost Structure Definition sin guardar cambios
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward backCostStructure(FordActionMapping mapping,
                                           ActionForm actionForm,
                                           HttpServletRequest request,
                                           HttpServletResponse response,
                                           WebSession webSession,
                                           ActionMessages msgs,
                                           ActionMessages warns,
                                           ActionMessages errorMsgs) {

        return mapping.findForward("success");
    }

}
